package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


public class SimpleRedisLock implements ILock {

    private String name;

    private StringRedisTemplate stringRedisTemplate;

    public static final String KEY_PREFIX = "lock:";

    //线程ID本来在JVM里创建是一个递增的数，不同节点下的线程可能重复
    //在各自JVM下创建线程ID头，这样不同JVM下的线程的加的锁能够区分开
    public static final String ID_PREFIX = UUID.randomUUID().toString() + "-";
    public static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 尝试获取锁
     *
     * @param timeOutSec
     * @return
     */
    @Override
    public boolean tryLock(long timeOutSec) {
        //1.获取当前线程ID
        long id = Thread.currentThread().getId();

        //2.获取锁
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, ID_PREFIX + id, timeOutSec, TimeUnit.SECONDS);

        //3.返回,这里拆箱要判断是否有空指针异常（redis宕机时返回空）
        return BooleanUtil.isTrue(flag);
    }

    @Override
    public void unLock() {
        //调用Lua脚本释放锁
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId());
    }


//    @Override
//    public void unLock() {
//        //1.获取当前线程ID标识
//        String currentThreadId = ID_PREFIX + Thread.currentThread().getId();
//
//        //2.获取锁中存储的线程ID标识
//        String lockThreadId = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
//
//        //3.只有当加锁的线程与解锁的线程一致时才可解锁
//        if(currentThreadId.equals(lockThreadId)){
//            stringRedisTemplate.delete(KEY_PREFIX + name);
//        }
//    }
}
